//
//  AppDelegate.swift
//  weibo10
//
//  Created by 猎人 on 15/10/14.
//  Copyright © 2015年 hunter. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultRootViewController
        window?.makeKeyAndVisible()
//        print(isNewVersion)
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootViewControllerNotification, object: nil, queue: nil) { [weak self] (notification) -> Void in
            self?.window?.rootViewController = MainViewController()
        }
        return true
    }
    
    deinit{
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(
            self,   //监听者
            name: WBSwitchRootViewControllerNotification,  //监听的对象
            object: nil)   //发送通知的对象
    }
    
/// 设置全局外观
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = WBAppearanceTintColor
        UITabBar.appearance().tintColor = WBAppearanceTintColor
    }
}

// MARK: - 界面切换
extension AppDelegate {
    
    private var defaultRootViewController: UIViewController {
        if UserAccountViewModel.sharedUserAccount.userLogon {
            return isNewVersion ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    
    
    /// 判断是否为新版本
    private var isNewVersion: Bool {
        
        // 1. 当前的版本 - info.plist
        // print(NSBundle.mainBundle().infoDictionary)
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        print("当前版本 \(version)")
        
        // 2. `之前`的版本，把当前版本保存在用户偏好 - 如果 key 不存在，返回 0
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        print("之前版本 \(sandboxVersion)")
        
        // 3. 保存当前版本
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: sandboxVersionKey)
        
        return version > sandboxVersion
    }
}